/**
 * Created by yel on 4/28/16.
 */

/*********************************************************************************************
 *
 * ajax functions.
 *
 **********************************************************************************************/

function getServices() {
  var serviceList = $('.service-list');
  $(serviceList).children('li').remove();
  $.get('/api/gets', function(data, status) {
    console.log('status: ' + status);
    console.log(data);
    for(d in data) {
      user = data[d];
      console.log(data[d]);
      console.log(data[d].username);
      console.log(data[d].name);
      var li = document.createElement('li');
      $(li).attr('id', user.username + '-item');
      $(li).html('<span>用户名： ' + user.name + '</span>'
            + '<span class="service-passwd">密码： ********</span>'
            + '<a class="delete-service-button" href="javascript:;">删除</a>');
      $(serviceList).append(li);
    }
  });
}

function requestDeleteService(item) {
  var serviceName = $(item).attr('id');
  serviceName = serviceName.substr(0, serviceName.length - 5);
  $.get('/api/deleteService', {serviceName: serviceName}, function(data, status) {
     getServices();
  });
}

function requestAddService() {
 hideAddServiceContainer();
 var serviceName = $('.add-service-name-input').val();
 $('.add-service-name-input').val('');
 var servicePasswd = $('.add-service-passwd-input').val();
 $('.add-service-passwd-input').val('');
 $.get('/api/addService', {serviceName: serviceName, servicePasswd: servicePasswd}, function(data, status) {
   getServices();
 });
 showAddServiceButton();
}


function showAddServiceContainer() {
  $('.add-service-container').show();
}

function hideAddServiceContainer() {
  $('.add-service-container').hide();
}

function showAddServiceButton() {
  $('.add-service-button').show();
}
function hideAddServiceButton() {
  $('.add-service-button').hide();
}

$(document).ready(function() {
  getServices();

  $('body').on('click', '.delete-service-button', function() {
     requestDeleteService($(this).parents('li'));
  });

  $('body').on('click', '.add-service-button',  function() {
    $(this).hide();
    showAddServiceContainer();
  });

  $('body').on('click', '.confirm-add-service-button', function() {
    requestAddService();
  });
});